package com.collect.cameroon.zhiScene.zhiLogin.zhiFace;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.collect.cameroon.R;
import com.collect.cameroon.zhiBase.BaseActivity;
import com.collect.cameroon.zhiBean.zhiReceive.ZHIRLoginEntity;
import com.collect.cameroon.zhiBean.zhiSend.ZHISFaceEntity;
import com.collect.cameroon.zhiGlobal.zhiAppSettings.ZHIProjectRouter;
import com.collect.cameroon.zhiHelper.ZHIMainProcessHelper;
import com.collect.cameroon.zhiScene.zhiCheckIn.ZHICheckInReduce;
import com.collect.cameroon.zhiScene.zhiLogin.zhiFace.zhiLivenessUtil.LivenessIntentUtil;
import com.collect.cameroon.zhiScene.zhiWidget.zhiDialog.ZHIDialogMessage;
import com.collect.cameroon.zhiScene.zhiWidget.zhiNavigationBar.ZHINavigationBar;
import com.collect.cameroon.zhiScene.zhiWidget.zhiStepView.ZHINextStepView;

import java.util.List;

import butterknife.BindView;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

@SuppressLint("NonConstantResourceId")
@Route(path = ZHIProjectRouter.ZHI_FACE)
public class ZHIFaceActivity extends BaseActivity<ZHIFacePresenter> implements ZHIFaceContract.View, EasyPermissions.PermissionCallbacks, EasyPermissions.RationaleCallbacks {

    @BindView(R.id.btn_negtive)
    ZHINextStepView btn_negtive;

    @BindView(R.id.navigationBar)
    ZHINavigationBar navigationBar;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_face;
    }

    @Override
    protected void initInjector() {
        mActivityComponent.inject(this);
    }

    @Override
    protected void initView() {
        try {
            navigationBar.hideLeft().setCenterText("Face Detection");
            btn_negtive.setOnMenuItemDidChangedListener(item -> getNeedPermissions());

            // 测试
            onUploadImageInfo("https://testfaceimg.jpg");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onGetErrorInfo(String methodName) {

    }

    @Override
    public void onUploadImageInfo(String url) {
        try {
            if (!TextUtils.isEmpty(url)) {
                if (mPresenter != null) {
                    mPresenter.saveFaceImageInfo(getActivity(), new ZHISFaceEntity(url));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onSaveFaceImageInfo() {
        try {
            //设置人脸成功
            ZHIMainProcessHelper.getInstance().getLoginEntity().setLiveFlag("NO");

            //判断是否需要打卡
            if (ZHIMainProcessHelper.getInstance().getZHIRCheckInOutEntity() != null && ZHIMainProcessHelper.getInstance().getZHIRCheckInOutEntity().isToCheckIn()) {
                ZHIDialogMessage.showDialog(getActivity(), "Tips", "You haven't clocked in for work today", false, true, tag -> {
                    ZHICheckInReduce.mFromLoginSuccess = true;
                    ZHIProjectRouter.toCheckInForLogin();
                });
            } else {
                handlerLoginResult();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onRationaleAccepted(int requestCode) {
        getNeedPermissions();
    }

    @Override
    public void onRationaleDenied(int requestCode) {

    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            //当从软件设置界面，返回当前程序时候
            case AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE: {
                //执行Toast显示或者其他逻辑处理操作
                getNeedPermissions();
                break;
            }
            case LivenessIntentUtil.REQUEST_CODE_FACE: {
                Log.d(TAG, "onActivityResult: REQUEST_CODE_FACE");
                if (resultCode == RESULT_OK) {
                    String frontImageFilePath = LivenessIntentUtil.getInstance().detectFilePath;
                    //上传图片
                    if (mPresenter != null) {
                        mPresenter.uploadImageInfo(getActivity(), frontImageFilePath);
                    }

//                    boolean isDetectSuccess = LivenessIntentUtil.getInstance().isDetectSuccess;
//                    if (isDetectSuccess) {
//                        String frontImageFilePath = LivenessIntentUtil.getInstance().detectFilePath;
//                        //上传图片
//                        mPresenter.uploadImageInfo(getActivity(), frontImageFilePath);
//                    } else {
//                        //上传失败信息
//                    }
                }
                break;
            }
        }
    }

    public void getNeedPermissions() {
        //测试
//        ASCallLogBuilder.setLog(true);
//        ArrayList<ASCallLogInfoBean> list = ASCallLogInfo.getLast10MinCallList(MyApplication.getAppContext());

        EasyPermissions.requestPermissions(this, getString(R.string.face_permissions), RC_CAMERA_AND_STORAGE, reqPerms);
    }

    private static final int RC_CAMERA_AND_STORAGE = 111;
    private static final String[] reqPerms = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA
    };

    @AfterPermissionGranted(RC_CAMERA_AND_STORAGE)
    public void allPass() {
        try {
            LivenessIntentUtil.getInstance().startFaceRecog(getActivity(), LivenessIntentUtil.REQUEST_CODE_FACE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handlerLoginResult() {
        try {
            ZHIRLoginEntity mZHIRLoginEntity = ZHIMainProcessHelper.getInstance().getLoginEntity();
            if (mZHIRLoginEntity != null) {
                //客服界面
                if (mZHIRLoginEntity.isCustomerFlag()) {
                    //电召界面
                    if (mZHIRLoginEntity.isCustomerWhitelistFlag()) {
                        ZHIProjectRouter.toRecallV2();
                        return;
                    }

                    //客服界面
                    ZHIProjectRouter.toCustomerServiceV2();
                    return;
                }

                //客服组长界面
                if (mZHIRLoginEntity.isCustomerDGroupFlag()) {
                    //客服界面
                    ZHIProjectRouter.toCustomerServiceAdmin();
                    return;
                }

                //电销界面
                if (mZHIRLoginEntity.isDxFlag()) {
                    ZHIProjectRouter.toRootTelemarketing();
                    return;
                }

                //电核界面
                if (mZHIRLoginEntity.isDhFlag()) {
                    ZHIProjectRouter.toRootDs();
                    return;
                }

                //单人审核界面
                if (mZHIRLoginEntity.isWholeKefuFlag()) {
                    ZHIProjectRouter.toRootAuditer();
                    return;
                }

                // 全流程客服审核员
                if (mZHIRLoginEntity.isWholeKefuAuditorFlag()) {
                    ZHIProjectRouter.toRootAuditerReview();
                    return;
                }

                // 全流程客服D0
                if (mZHIRLoginEntity.isWholeKefuD0Flag()) {
                    ZHIProjectRouter.toRootAuditerD0();
                    return;
                }

                // 全流程客服D1
                if (mZHIRLoginEntity.isWholeKefuD1Flag()) {
                    ZHIProjectRouter.toRootAuditerD1();
                    return;
                }

                // 全流程客服B1
                if (mZHIRLoginEntity.isWholeKefuB1Flag()) {
                    ZHIProjectRouter.toRootAuditerB1();
                    return;
                }

                //改钱包客服角色界面
                if (mZHIRLoginEntity.isCustomerChangeWalletFlag()) {
                    ZHIProjectRouter.toRootDsChangeWallet();
                    return;
                }

                //大组长催收界面
                if (mZHIRLoginEntity.isBigGroupFlag()) {
                    ZHIProjectRouter.toRootBigGroup();
                    return;
                }

                //催收界面
                if (mZHIRLoginEntity.isGroupFlag()) {
                    if (mZHIRLoginEntity.isLevelB1()) {
                        ZHIProjectRouter.toRootGroupB1();
                    } else if (mZHIRLoginEntity.isLevelB2()) {
                        ZHIProjectRouter.toRootGroupB2();
                    } else {
                        ZHIProjectRouter.toRootGroup();
                    }
                } else {
                    if (mZHIRLoginEntity.isLevelB1()) {
                        ZHIProjectRouter.toRootMemberB1();
                    } else if (mZHIRLoginEntity.isLevelB2()) {
                        ZHIProjectRouter.toRootMemberB2();
                    } else {
                        ZHIProjectRouter.toRootMember();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}